<template>
  <div id="home">
    <!-- 导航 -->
    <nav-temp>
      <template v-slot:nav>
        <li
          :key="index"
          v-for="(itme, index) in top"
          :class="{ liBox: index == box }"
          @click="liBox(index)"
        >
          {{ itme }}
        </li>
      </template>
      <template v-slot:navname>
        <div class="out">
          欢迎~<span>{{ user.name }}</span>
        </div>
      </template>
    </nav-temp>

    <!-- 页头 -->
    <div class="Rotation">
      <div class="rot-img">
        <img src="../../assets/img/home/we.jpg" />
      </div>

      <div class="rot-greet">
        <div class="greet">
          <span>{{ grett }},{{ user.name }}</span>
          <p>
            今天很短，但今天很重要，漂亮的今天，不仅可以把昨天的辉煌变成明天的辉煌，更可以把昨天的失败变成明天的成功。早安，加油！
          </p>
        </div>

        <input type="text" class="text" />
        <!-- 个人社交平台 -->
        <div class="icon">
          <i class="iconfont icon-qq" title="点击复制">
            <p>1517291947</p>
          </i>
          <i class="iconfont icon-shejiaotubiao-01" title="点击复制">
            <p>wxid_l8fw72xb929x22</p>
          </i>
          <i class="iconfont icon-gitee-fill-round" title="点击复制">
            <p>https:&#47;&#47;gitee.com&#47;jianghuohua</p>
          </i>
          <i class="iconfont icon-youjian1" title="点击复制">
            <p>1517291947@.com</p>
          </i>
        </div>
      </div>
    </div>
    <!-- 内容 -->
    <div id="main" class="width">
      <!-- 发表文章组件 -->
      <div style="float: left">
        <div class="main-mage">
          <!-- 评论 -->
          <div class="textarea">
            <textarea
              class="input"
              placeholder="请输入"
              @focus="putFocus"
              @blur="putBlur"
              :value="idea"
            >
            </textarea>
          </div>
          <!-- 图片预览 -->
          <div class="preview">
            <div class="preview-son" :key="index" v-for="(item, index) in sum">
              <i
                class="iconfont icon-guanbi2 img-icon"
                @mousedown="imgicon(index)"
              ></i>
              <div class="img" @click="big"></div>
            </div>
          </div>
          <div id="function-but">
            <!-- 表情包 -->
            <button class="biaoqing-but but" @focus="biaoqing">
              <i class="iconfont icon-haopingxiaolian-xianxing biaoqing i"></i>
              <emo v-if="emoif" @icomDown="modTtextarea"></emo>
            </button>
            <!-- 上传图片 -->
            <button class="huaban-but but" @click="upimg">
              <input
                type="file"
                id="file"
                name="file"
                @change="file"
                accept=".jpg, .jpeg, .bmp, .gif, .png, .heif, .heic"
                style="display: none"
                multiple
              />
              <i class="iconfont icon-tianjiatupian_huaban huaban"></i>
            </button>
            <!-- 发送评论 -->
            <button class="comment" @click="comment">发送</button>
            <!-- <button @click="add">点击</button> -->
          </div>
        </div>
        <!-- 文章 -->
        <Article></Article>
      </div>

      <!-- 个人信息栏 -->
      <state></state>
    </div>
  </div>
</template>

<script>
// vuex
import userInfo from "@/store/user/userInfo";
// 网络请求封装
import { request } from "@/network/request";
import emo from "common/emoji/emo.vue";
// 自定义 “弹出框”
import prompt from "common/prompt/prompt";
import NavTemp from "common/nav/NavTemp";
// 个人信息栏
import State from "content/state/state.vue";
import Article from "content/article/Article.vue";

export default {
  name: "#home",
  data() {
    return {
      //存储用户ID
      identity: "",
      // 导航
      top: ["主页", "主题", "相册", "自学路线", "个人"],
      // 切换背景颜色
      bgCol: [],
      // 导航获取焦点时
      box: 0,
      // 问候语
      grett: "早上好",
      // 表情包的显示隐藏
      emoif: false,
      // 拼接表情包
      idea: "",
      sum: 0,
      num: 0,
      // 将一个个文件给formData
      for: [],
      // 存储上传文件
      formData: null,
      src: ["a", "b", "c"],
    };
  },
  setup() {
    let { user, add } = userInfo();
    return {
      user,
      add,
    };
  },
  methods: {
    liBox(index) {
      this.box = index;
    },
    downshow() {
      $("#emo").show();
    },
    // 点击显示表情框
    biaoqing() {
      // 为true创建组件
      this.emoif = true;
      $("#emo").show();
      // 显示表情框后获取焦点
      $("#emo").focus();
    },
    // 子传递，表情数据
    modTtextarea(icon) {
      this.idea += icon;
    },
    // 评论框获取焦点
    putFocus() {
      // 改变边框颜色
      $(".textarea").css("border", "1px solid rgba(1, 140, 233, 0.8)");
      $(".input").bind("input propertychange", () => {
        let tex = $(".input").val();
        this.idea = tex;
      });
    },
    // 评论框失去焦点
    putBlur() {
      $(".textarea").css("border", "1px solid rgba(1, 140, 233, 0)");
      // this.idea = tex;
    },

    // 上传图片框
    file(e) {
      let file = e.target.files;
      if (file && file.length) {
        let nums = $(".preview-son").length;
        let URL = window.URL || window.webkitURL;
        let imgURL = [];
        // 本地图片路径

        for (let i = 0; i <= file.length - 1; i++) {
          imgURL[i] = URL.createObjectURL(file[i]);
          this.sum += 1;
          let leng = this.for.length;
          setTimeout(() => {
            // console.log(this.for.length);
            for (let i = 0; i <= file.length - 1; i++) {
              $(".preview-son .img")
                .eq(i + leng)
                .append('<img src="" alt="">');
              $(".preview-son .img img")
                .eq(i + leng)
                .attr("src", imgURL[i]);
            }
            $("#file").val("");
          }, 500);
        }
      }

      // 多图上传
      let files = e.target.files;
      // console.log(files);
      this.formData = new FormData();

      if (files.length === 1) {
        this.for.push(files[0]);
      } else {
        for (let i in files) {
          if (i < files.length) {
            this.for.push(files[i]);
          }
        }
      }
    },
    // 代替点击上传图片
    upimg() {
      $("#file").click();
    },
    // 图片放大
    big(index) {
      console.log(index);
    },
    // 移除预览图片 -----------------------------------------------------------------------------------------------------------
    imgicon() {
      let leth = document.querySelectorAll(".img-icon");

      for (let i = 0; i < leth.length; i++) {
        //将i的下标赋值到li的index上
        leth[i].index = i;
        leth[i].onclick = () => {
          // index = i;
          delete this.for[i];
          leth[i].parentElement.remove();
        };
      }
    },
    // 点击发送评论 -----------------------------------------------------------------------------------------------------------
    comment() {
      if (this.idea === null || this.idea === "") return alert("表单不可为空");

      let userInfo = {
        identity: this.user.identity,
        name: this.user.name,
        image: this.user.image,
        article: this.idea,
      };

      // 文章上传
      request({
        url: "/article",
        params: userInfo,
      })
        .then((res) => {
          console.log(res);
          if (this.for.length > 0) {
            // 插入要上传的图片
            this.for.forEach((val, dex, arr) => {
              if (val) {
                this.formData.append("file", val);
              }
            });
            // 图片上传
            request({
              url: "/upload",
              data: this.formData,
              method: "post",
              headers: {
                "Content-Type": "multipart/form-data",
              },
            });
          }
        })
        .then((res) => {
          // 上传图片成功后
          $(".preview-son").remove();
          this.formData = null;
          this.for = [];
          this.idea = "";
        });
    },
  },
  // 页面初始化时
  beforeCreate() {
    request({
      url: "/user",
    })
      .then((res) => {
        let top1;
        if (res.status !== 0) {
          var bodyEl = document.body;
          top1 = window.scrollY;
          bodyEl.style.position = "fixed";
          bodyEl.style.top = -top1 + "px";
          prompt.session();
          setTimeout(() => {
            this.$router.push("login");
            bodyEl.style.position = "";
            bodyEl.style.top = "";
            window.scrollTo(0, top1); // 回到原先的top
            prompt.session();
          }, 3000);
        } else if (res.status === 0) {
          // console.log(res.user[0]);
          this.identity = res.user[0].identity;
          this.add(res.user[0]);
          console.log(this.user.push(res.user[0]));
        }
      })
      .catch(() => {});
  },
  created() {
    $(document).ready(() => {
      // 移除预览图片

      // 点击自动复制
      $(".icon i").on("click", function (event) {
        event.preventDefault();
        let text = $(this).children("p").text();
        // const texts = $(this);
        $(".text").val(text).select();
        document.execCommand("Copy");
        prompt.su(this, "复制成功");
      });

      $(".input").text(null);

      let white = $(window).outerWidth();
      if (white <= 610) {
        $("#main").removeClass("width");
      } else {
        $("#main").addClass("width");
      }

      let son = $(".preview-son").width();
      $(".preview-son").height(son);
      $(window).resize(function () {
        let white = $(window).outerWidth();
        if (white <= 610) {
          $("#main").removeClass("width");
        } else {
          $("#main").addClass("width");
        }
        let son = $(".preview-son").width();
        $(".preview-son").height(son);
      });
    });
  },
  components: {
    NavTemp,
    emo,
    State,
    Article,
  },
};
</script>
<style scoped>
@import url("./home.css");
</style>

